package com.godme.concurrent.pattern;


import java.util.LinkedList;
import java.util.concurrent.atomic.AtomicInteger;

public class GuardedSuspensionPattern {

    public static class Queue<T> {
        private final java.util.Queue<T> queue = new LinkedList<>();

        public synchronized T get() {
            while (queue.peek() == null) {
                try {
                    wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            return queue.remove();
        }

        public synchronized void put(T value) {
            queue.offer(value);
            notifyAll();
        }
    }


    public static class ProducerThread extends Thread {

        private final AtomicInteger counter;

        private final Queue<Integer> queue;

        public ProducerThread(String name, AtomicInteger counter, Queue<Integer> queue) {
            super(name);
            this.counter = counter;
            this.queue = queue;
        }

        @Override
        public void run() {
            int value;
            for (int i = 0; i < 100; i++) {
                value = counter.getAndIncrement();
                queue.put(value);
                System.err.println(getName() + " :: " + value);
            }
        }
    }

    static class ConsumerThread extends Thread {
        private final Queue<Integer> queue;

        public ConsumerThread(String name, Queue<Integer> queue) {
            super(name);
            this.queue = queue;
        }

        @Override
        public void run() {
            for (int i = 0; i < 1000; i++) {
                System.err.println(getName() + " :: " + queue.get());
            }
        }
    }

    public static void main(String[] args) {
        Queue<Integer> queue = new Queue<>();
        AtomicInteger counter = new AtomicInteger();
        for (int i = 0; i < 2; i++) {
            new ProducerThread("producer"+i, counter, queue).start();
        }
        for (int i = 0; i < 5; i++) {
            new ConsumerThread("consumer"+i, queue).start();
        }
    }

}
